const koa = require("koa");
const app = new koa();
const convert = require('koa-convert');

// 全局处理工具
const app_config = require("./app_config.conf");
require("../tools/_include.t");
require("../tools/_Array.t");

// session
const session = require("koa-session");
app.keys = ['keys', 'keykeys'];
app.use(convert(session(app)));

// 日志文件管理
const log4js = require('koa-log4');
app_config.is_dev ? true : log4js.configure("server/log4js.json");
app.use(log4js.koaLogger(log4js.getLogger('app'), { level: 'auto' }));

// co
global.co = require("co");

const cors = require("koa-cors")({ // 中间件，只允许部分域名访问此域
    origin: function(ctx) {
        // console.log(ctx.headers['x-forwarded-for'] ||
        // ctx.connection.remoteAddress ||
        // ctx.socket.remoteAddress ||
        // ctx.connection.socket.remoteAddress)
        _origin = ctx.header.origin || "*";
        // console.log("_origin:", _origin)
        // console.log(ctx)
        if (_origin == "null" || _origin.indexOf("fangche") > -1 || _origin.indexOf("chrome-extension") > -1 || _origin.indexOf("dotnar.com") > -1 || _origin.indexOf("127.0.0.1") > -1 || _origin.indexOf("shengyi8888.com") > -1 || _origin.indexOf("localhost:") > -1 || _origin == "*") {
            return _origin;
        };
        console.log("?");
        return "*";
    },
    credentials: true,
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS"
});
app.use(convert(cors));

// 中间件，判断方法接口是否被访问域名执行
app.use(co.wrap(function*(ctx, next) {
    var _url = ctx.request.url;
    var _origin = ctx.header.origin || "*";
    if (_origin == "null" || _origin.indexOf("fangche") > -1 || _origin.indexOf("chrome-extension") > -1 || _origin.indexOf("dotnar.com") > -1 || _origin.indexOf("127.0.0.1") > -1 || _origin.indexOf("shengyi8888.com") > -1 || _origin.indexOf("localhost:") > -1 || _origin == "*") {
        // if (_url.indexOf("/user/") == 0 && !ctx.session.user) { // 执行用户接口时，判断用户数是否已经登陆
        //     ctx.body = {
        //         type: "error",
        //         toString: "用户未登录"
        //     };
        //     return;
        // };
        yield next();
    };
}));


// qiniu
require("../tools/qiniu.t");

// bmob
global.bmob = require("../tools/Bmob.t");

// mongodb
const MongoClient = require('mongodb').MongoClient;
global.ObjectID = require('mongodb').ObjectID;

co(function*() {
    global.mongo = require("../tools/mongo.t");
    global.db = yield MongoClient.connect('mongodb://127.0.0.1:27017/shengyibbs');
    const router = yield require("../complex/complex");

    router.router.get("/allApis", function*() {
        router.apis.push({
            name: "getAllApis",
            content: "获取所有接口描述",
            apiroot: "/allApis"
        });
        this.body = router.apis;
    });
    router.router.post("/qiniucallback", function*() {
        console.log(yield parse(this.request));
        this.body = { stastus: "ok" };
    });

    console.log("api:", "/qiniucallback")
    app.use(convert(router.router.routes()));
    app.use(convert(router.router.allowedMethods()));

    app.listen(1212);
    console.log(("server start at 1212," + new Date().toLocaleString()).data);
}).catch(e => {
    console.log("start err:", e);
    console.log(new Date().toLocaleString());
});
